import type { ApiResponse } from './types/common'
import { message } from '@/utils/message'
import { storage } from '@/utils/storage'
import { ref } from 'vue'
import { ResponseCode } from './types/common'

// 创建计数器用于跟踪loading状态
const loadingCount = ref(0)

// 显示loading
function showLoading() {
  if (loadingCount.value === 0) {
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
  }
  loadingCount.value++
}

// 隐藏loading
function hideLoading() {
  loadingCount.value--
  if (loadingCount.value === 0) {
    uni.hideLoading()
  }
}

interface RequestOptions extends UniApp.RequestOptions {
  loading?: boolean
  mock?: boolean
}

// 创建请求实例
async function request<T>(options: RequestOptions) {
  const {
    url,
    loading = true,
    ...requestOptions
  } = options

  // 显示loading
  loading && showLoading()

  // 配置请求头
  const header = {
    'Content-Type': 'application/json',
    ...requestOptions.header,
  }

  // 获取本地存储的token
  const token = storage.get('token')
  if (token) {
    header.TOKEN = `${token}`
  }

  try {
    const response = await new Promise<UniApp.RequestSuccessCallbackResult>((resolve, reject) => {
      let baseUrl = import.meta.env.VITE_API_BASE_URL + url.replace('/api', '')

      if (import.meta.env.VITE_API_MOCK_BASE_URL) {
        baseUrl = import.meta.env.VITE_API_MOCK_BASE_URL + url
      }

      uni.request({
        ...requestOptions,
        url: baseUrl,
        header,
        success: (res) => {
          // 处理 HTTP 状态码错误
          if (res.statusCode >= 400) {
            const errorMsg = {
              404: '请求的资源不存在',
              401: '未授权',
              403: '禁止访问',
              500: '服务器错误',
              502: '网关错误',
              503: '服务不可用',
              504: '网关超时',
            }[res.statusCode] || '请求失败'

            message.error(errorMsg)
            reject(new Error(errorMsg))
            return
          }
          resolve(res)
        },
        fail: (err) => {
          message.error('网络请求失败，请检查网络连接')
          reject(err)
        },
        complete: () => {
          loading && hideLoading()
        },
      })
    })

    const result = response.data as ApiResponse<T>

    // 如果请求成功
    if (result.code === ResponseCode.Success) {
      return [null, result] as [null, ApiResponse<T>]
    }

    // 如果请求失败
    return [result, null] as [ApiResponse<T>, null]
  }
  catch (error) {
    console.log('请求错误：', error)
    loading && hideLoading()
    return [error as Error, null] as [Error, null]
  }
}

// 导出 HTTP 方法
export const http = {
  get: <T = any>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'data' | 'method'>) => {
    return request<T>({
      url,
      data,
      method: 'GET',
      ...options,
    })
  },

  post: <T = any>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'data' | 'method'>) => {
    return request<T>({
      url,
      data,
      method: 'POST',
      ...options,
    })
  },

  put: <T = any>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'data' | 'method'>) => {
    return request<T>({
      url,
      data,
      method: 'PUT',
      ...options,
    })
  },

  delete: <T = any>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'data' | 'method'>) => {
    return request<T>({
      url,
      data,
      method: 'DELETE',
      ...options,
    })
  },
}
